import { getUserInfo, login } from '@/api/user'
import { setToken, getToken, removeToken, setUserKey, getUserKey, removeUserKey } from '@/utils/storage'
export default {
  namespaced: true,
  state () {
    return {
      token: getToken(),
      userInfo: getUserKey()
    }
  },
  getters: {

  },
  mutations: {
    setToken (state, token) {
      state.token = token
    },
    removeToken (state, token) {
      state.token = null
      removeToken(token)
    },
    getUserInfo (state, userInfo) {
      state.userInfo = userInfo
    },
    removeUserInfo (state, userInfo) {
      state.userInfo = null
      removeUserKey()
    }
  },
  actions: {
    async loginAction (context, data) {
      const token = await login(data.Vcode, data.telephone, data.password)
      context.commit('setToken', token)
      context.dispatch('getUserInfo')
      setToken(token)
    },
    async getUserInfo (context) {
      const userInfo = await getUserInfo()
      console.log(userInfo)
      setUserKey(userInfo)
      context.commit('getUserInfo', userInfo)
    },
    logoutAction (context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
    }
  }
}
